import utils from '../../core/utils';
import apiProvider from './apiProvider';
import current from '../../core/current';
import apiKeyInfo from '../../model/common/apiKeyInfo';

export default class apiInfo {
  constructor(url: string, conditions?: string, needKey?: boolean, signType: number = 0) {
    this.url = url;
    this.conditions = conditions;
    if (needKey)
      this.needKey = needKey;
    this.signType = signType;
  }

  private signType: number = 0;

  private _url: string;

  public get url() {
    return this._url;
  }

  public set url(url: string) {
    this._url = url;
  }

  private _needKey: boolean = false;

  public get needKey() {
    return this._needKey;
  }

  public set needKey(needKey: boolean) {
    this._needKey = needKey;
  }

  private _conditions: string;

  public get conditions() {
    return this._conditions;
  }

  public set conditions(conditions: string) {
    this._conditions = conditions;
  }

  private _buildVer: string = apiProvider.Build5;

  public get buildVer() {
    return this._buildVer;
  }

  public set buildVer(buildVer: string) {
    this._buildVer = buildVer;
  }

  async toString(params: boolean = true, keyInfo: apiKeyInfo = apiProvider.AndroidKey): Promise<string> {
    return new Promise(async (resolve) => {
      let builder = '';
      if (this._needKey && current.instance.isLogin) {
        if (!this.conditions.includes('uid'))
          builder += `mid=${current.instance.mid}&`;
        builder += `access_key=${apiProvider.accessKey}&`;
      }
      if (params) {
        builder += 'actionKey=appkey&';
        builder += `appkey=${keyInfo.appkey}&`;
        builder += `build=${this._buildVer}&`;
        builder += 'mobi_app=android&';
        builder += 'platform=android&';
        builder += 'device=android&';
        builder += `ts=${apiProvider.timeSpanSeconds}&`;
      }
      if (!utils.isEmpty(this._conditions)) {
        if (this._conditions.startsWith('&'))
          builder += `${this._conditions.substring(1, this._conditions.length)}&`;
        else
          builder += `${this._conditions}&`;
      }
      if (this.signType == 0)
        builder += `sign=${apiProvider.getSign(builder, keyInfo)}`;
      else
        builder += `w_rid=${await apiProvider.getWbiSign(builder)}`;
      resolve(`${this.url}?${builder}`);
    });
  }
}